package com.wwtech.epp.ui.activity.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ninjia.ninjiabaselibrary.view.RxDialogWheelYearMonthDayMe;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseFragment;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.AttachmentBean;
import com.wwtech.epp.entity.ProjectEntity;
import com.wwtech.epp.ui.activity.friend.AddManagerActivity;
import com.wwtech.epp.ui.activity.work.component.DaggerNewTaskComponent;
import com.wwtech.epp.ui.activity.work.contract.NewTaskContract;
import com.wwtech.epp.ui.activity.work.module.NewTaskModule;
import com.wwtech.epp.ui.activity.work.presenter.NewTaskPresenter;
import com.wwtech.epp.ui.adapter.work.AttachmentAdapter;
import com.wwtech.epp.utils.StringUitl;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.utils.UIUtils;
import com.wwtech.epp.view.CustomPopWindow;
import com.wwtech.epp.view.GlideCircleTransform;
import com.wwtech.epp.view.ProjectMemberView;
import com.wwtech.epp.view.datepicker.NumericWheelAdapter;
import com.wwtech.epp.view.datepicker.WheelView;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.activity.FileListActivity;
import io.rong.imkit.activity.FileManagerActivity;
import io.rong.imkit.model.FileInfo;
import io.rong.imkit.utils.FileTypeUtils;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/09/16 16:06:07
 */

public class NewTaskFragment extends BaseFragment implements NewTaskContract.View {

    private static final String ARG_TYPE = "arg_type";
    public static final int CHECKMANAGE = 1;
    @Inject
    NewTaskPresenter mPresenter;

    @Inject
    AttachmentAdapter attachmentAdapter;

    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.tv_task_end_time)
    TextView tvTaskEndTime;
    @BindView(R.id.tv_task_other)
    TextView tvTaskOther;
    @BindView(R.id.project_member_view)
    ProjectMemberView projectMemberView;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.tv_attachment)
    TextView tvAttachment;
    @BindView(R.id.add_attachment)
    ImageView addAttachment;
    @BindView(R.id.attachmentRecyclerView)
    RecyclerView attachmentRecyclerView;
    private WheelView wheelView;
    private NumericWheelAdapter xiangmuAdapter;

    ArrayList<String> projectIds = new ArrayList<>();

    int projectIdPosition = -1;
    private RxDialogWheelYearMonthDayMe mRxDialogWheelYearMonthDay;

    String managerId = "";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_task, null);
        ButterKnife.bind(this, view);
        Bundle mBundle = getArguments();
        attachmentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        attachmentRecyclerView.setAdapter(attachmentAdapter);
        attachmentRecyclerView.setNestedScrollingEnabled(false);
        attachmentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (view.getId()) {
                    case R.id.iv_opreate:
                        attachmentAdapter.getData().remove(i);
                        attachmentAdapter.notifyDataSetChanged();
                        if (attachmentAdapter.getData().size() != 0) {
                            tvAttachment.setText("附件(" + attachmentAdapter.getData().size() + ")");
                        } else {
                            tvAttachment.setText("附件");
                        }
                        break;
                    default:
                        break;
                }
            }
        });
//        attachmentAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
//                showDialog(i);
//                return true;
//            }
//        });
        return view;
    }

    private void showDialog(int position) {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        View view1 = View.inflate(getActivity(), R.layout.two_choose_dialog, null);
        alertDialog.setView(view1);
        alertDialog.setCancelable(true);
        TextView tv_title = (TextView) view1.findViewById(R.id.content);
        tv_title.setText("删除该条附件？");
        TextView cancal = (TextView) view1.findViewById(R.id.cancal);
        TextView sure = (TextView) view1.findViewById(R.id.sure);
        cancal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                attachmentAdapter.getData().remove(position);
                tvAttachment.setText("附件 (" + attachmentAdapter.getData().size() + ")");
                attachmentAdapter.notifyDataSetChanged();
            }
        });
        alertDialog.show();
    }

    private void upLoadFile(int position) {
        mPresenter.upLoadFile(attachmentAdapter.getData().get(position).getName(), attachmentAdapter.getData().get(position).getLocalUrl(), position);
    }


    public static NewTaskFragment newInstance(String param) {
        NewTaskFragment fragment = new NewTaskFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TYPE, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent() {
        DaggerNewTaskComponent
                .builder()
                .appComponent(((AppConfig) getActivity().getApplication()).getApplicationComponent())
                .newTaskModule(new NewTaskModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(NewTaskContract.NewTaskContractPresenter presenter) {
        mPresenter = (NewTaskPresenter) presenter;
    }

    @Override
    protected void initDataFromLocal() {

    }

    public String getSDCardPath() {
        String SDCardDefaultPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        if(SDCardDefaultPath.endsWith("/")) {
            SDCardDefaultPath = SDCardDefaultPath.substring(0, SDCardDefaultPath.length() - 1);
        }
        return SDCardDefaultPath;
    }


    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void onProjectManagerBack(Friend friend) {
        projectMemberView.getNickTextview().setText(friend.getNickname());
        projectMemberView.setSetInfo(true);
        managerId = friend.getUserId();
        Glide.with(this)
                .load(friend.getAvatar())
                .transform(new GlideCircleTransform(getActivity()))
                .into(projectMemberView.getAvaterImg());
    }

    @Override
    public void setListData(ProjectEntity projectEntity) {
        ArrayList<String> datalist = new ArrayList<>();
        for (ProjectEntity.DataBean.ListBean s : projectEntity.getData().getList()) {
            datalist.add(s.getProjectName());
            projectIds.add(s.getProjectId() + "");
        }
        xiangmuAdapter = new NumericWheelAdapter(getActivity(), 0, datalist.size() - 1, "", datalist);
        showWheelView(tvTaskOther, "选择项目");
    }

    @Override
    public void jobAddSuccess() {
        ToastUtil.displayShortToast("任务新建成功");
        tvTaskEndTime.setText("");
        tvTaskOther.setText("");
        etTitle.setText("");
        etContent.setText("");
        tvAttachment.setText("附件");
        projectIdPosition = -1;
        attachmentAdapter.getData().clear();
        attachmentAdapter.notifyDataSetChanged();
        projectMemberView.clear();
        EventBus.getDefault().post("create");
    }

    @Override
    public void loadFileSuccess(int position, String loadUrl) {
        attachmentAdapter.getData().get(position).setUrl(loadUrl);
        attachmentAdapter.getData().get(position).setState(AttachmentBean.State.loaded);
        attachmentAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 730) {
            if (data == null) {
                return;
            }
            HashSet<FileInfo> files = (HashSet<FileInfo>) data.getSerializableExtra("selectedFiles");
            for (FileInfo file : files) {
                KLog.i(file.getFilePath());
                KLog.i(file.getFileName());
                AttachmentBean attachmentBean = new AttachmentBean();
                attachmentBean.setLocalUrl(file.getFilePath());
                attachmentBean.setName(file.getFileName());
                attachmentBean.setState(AttachmentBean.State.select);
                attachmentAdapter.addData(attachmentBean);
            }
            for (int i = 0; i < attachmentAdapter.getData().size(); i++) {
                if (attachmentAdapter.getData().get(i).getState() != AttachmentBean.State.loaded) {
                    upLoadFile(i);
                }
            }
            if (attachmentAdapter.getData().size() != 0) {
                tvAttachment.setText("附件（" + attachmentAdapter.getData().size() + "）");
            }
            return;
        }
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.tv_task_end_time, R.id.tv_task_other, R.id.project_member_view, R.id.tv_confirm, R.id.add_attachment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_task_end_time:
                initWheelYearMonthDayDialog();
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.tv_task_other:
                mPresenter.getProjectListFromServer("我的项目", 1, 100);
                break;
            case R.id.project_member_view:
                Intent intent = new Intent(getActivity(), AddManagerActivity.class);
                intent.putExtra("position", "-1");
                startActivityForResult(intent, CHECKMANAGE);
                break;
            case R.id.tv_confirm:
                if (StringUitl.isNotEmpty(etTitle, "请输入标题")) {
                    if (StringUitl.isNotEmpty(etContent, "请输入内容")) {
                        if (StringUitl.isNotEmpty(tvTaskEndTime, "请选择任务期限")) {
                            if (!managerId.equals("")) {
                                preNewTask();
                            } else {
                                ToastUtil.displayShortToast("请选择负责人");
                            }
                        }
                    }
                }
                break;
            case R.id.add_attachment:
                Intent intent1 = new Intent(getActivity(), FileListActivity.class);
                intent1.putExtra("rootDirType", 101);
                intent1.putExtra("fileFilterType", 6);
                intent1.putExtra("fileTraverseType", 201);
                intent1.putExtra("rootDir", getSDCardPath());
                startActivityForResult(intent1, 730);
                break;
            default:
                break;
        }
    }

    private void preNewTask() {
        Map<String, String> map = new HashMap<>();
        if (projectIdPosition == -1) {
            ToastUtil.displayShortToast("请选择关联项目");
            return;
        }
        map.put("projectId", projectIds.get(projectIdPosition));
        map.put("deadline", tvTaskEndTime.getText().toString());
        map.put("ownerId", managerId);
        map.put("jobTitle", etTitle.getText().toString().trim());
        map.put("jobContent", etContent.getText().toString().trim());
        map.put("createrId", ContainValue.userLogin.getData().getUserId() + "");
        int count = 0;
        for (int i = 0; i < attachmentAdapter.getData().size(); i++) {
            if (attachmentAdapter.getData().get(i).getState() == AttachmentBean.State.loaded) {
                map.put("files[" + count + "].name", attachmentAdapter.getData().get(i).getName());
                map.put("files[" + count + "].url", attachmentAdapter.getData().get(i).getUrl());
                count ++;
            }
        }
        mPresenter.newTask(map);
        KLog.i(map);
    }

    private void showWheelView(View showview, String title) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(showview.getWindowToken(), 0);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.wheelview_layout, null);
        LinearLayout ll_content = (LinearLayout) view.findViewById(R.id.ll_content);
        ll_content.setAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.pop_manage_product_in));
        TextView submit = (TextView) ll_content.findViewById(R.id.submit);
        TextView tv_title = (TextView) ll_content.findViewById(R.id.tv_title);
        tv_title.setText(title);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomPopWindow.onBackPressed();
                if (xiangmuAdapter.getItemsCount() == 0) {
                    return;
                }
                tvTaskOther.setText(xiangmuAdapter.getItem(wheelView.getCurrentItem()));
                projectIdPosition = wheelView.getCurrentItem();
            }
        });
        wheelView = (WheelView) ll_content.findViewById(R.id.wheelview);
        wheelView.setViewAdapter(xiangmuAdapter);
        new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setClippingEnable(false)
                .setFocusable(true)
                .setView(view)
                .setContenView(ll_content)
                .size(UIUtils.getDisplayWidth(getActivity()), UIUtils.getDisplayHeigh(getActivity()))
                .create()
                .showAtLocation(showview, Gravity.CENTER, 0, 0);
    }

    private void initWheelYearMonthDayDialog() {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDayMe(getActivity(), 0, 0);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        String time = mRxDialogWheelYearMonthDay.getSelectorYear() + "-" + mRxDialogWheelYearMonthDay.getSelectorMonth() + "-" + mRxDialogWheelYearMonthDay.getSelectorDay() + "";
                        tvTaskEndTime.setText(time);
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

}